import os
import re
from datetime import datetime, timedelta
import tkinter as tk
from tkinter import filedialog, messagebox
from collections import Counter
import pandas as pd
import json

def askdirectory():
    root = tk.Tk()
    root.withdraw()
    folderpath = filedialog.askdirectory(title="请选择包含.log文件的文件夹")
    return folderpath


def select_output_file_path():
    root = tk.Tk()
    root.withdraw()
    file_path = filedialog.asksaveasfilename(
        defaultextension=".xlsx",
        filetypes=[("xlsx files", "*.xlsx"), ("All files", "*.*")],
    )
    return file_path
# 用于存储提取的数据
data_list = []
folder_path = askdirectory()
file_excel = select_output_file_path()
for filename in os.listdir(folder_path):
    if filename.endswith(".log"):
        file_path = os.path.join(folder_path, filename)
        
        # 打开日志文件并逐行读取
        with open(file_path, 'r', encoding='GB2312') as file:
            for line in file:
                # 使用正则表达式匹配以INFO开头的行，并提取JSON部分（可选步骤，取决于日志格式）
                match = re.search(r'INFO\s+.*\s*-\s*(\[.*?\])\s*-\s*(.*)', line)
                if match:
                    # 提取JSON字符串
                    json_str = match.group(2)
                    try:
                        # 解析JSON字符串
                        data = json.loads(json_str)
                        # 提取memo字段中的嵌套JSON，并再次解析
                        memo_data = json.loads(data['memo'])
                        # 提取lng、lat和Upload_time
                        lng = memo_data['data']['lng']
                        lat = memo_data['data']['lat']
                        updateTime = data['updateTime']
                        # 将提取的数据添加到列表中
                        data_list.append({'Lng': lng, 'Lat': lat, 'updateTime': updateTime})
                    except json.JSONDecodeError:
                        # 处理JSON解析错误（可选）
                        print(f"JSON解析错误: {line.strip()}")

# 使用pandas创建DataFrame
df = pd.DataFrame(data_list)


# 导出到Excel文件
df.to_excel(file_excel, index=False)

print(f"数据已成功导出到'{file_excel}'文件中。")